package hot;

import java.util.List;

/**
 * @author lakersUp
 * @Classname       合并k个有序链表
 * @Description     归并递归 或者 优先队列
 * @Date 2022/3/8 19:10
 * @Version 1.0
 */
public class Hot23mergeKLists {
    public ListNode mergeKLists(ListNode[] lists) {
        if(lists==null || lists.length==0){
            return new ListNode();
        }
        int right=lists.length-1;
        int left=0;
        return dfs(lists,left,right);
    }

    private ListNode dfs(ListNode[] lists, int left, int right) {
        if(left==right){
            return lists[left];
        }
        int mid=(left+right)/2;
        ListNode leftList = dfs(lists, left, mid);
        ListNode rightList = dfs(lists, mid + 1, right);
        return mergeTwoLists(leftList,rightList);
    }

    private ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode pre = new ListNode(-1);
        ListNode node=pre;

        while(list1!=null && list2!=null){
            if(list1.val<=list2.val){
                node.next=list1;
                node=node.next;
                list1=list1.next;
            }else {
                node.next=list2;
                node=node.next;
                list2=list2.next;
            }
        }
        if(list1==null){
            node.next=list2;
        }
        if(list2==null){
            node.next=list1;
        }
        return pre.next;
    }
}
